<template>
  <el-form class="account-node-form-add form-margin--mini"
           :model="form"
           :rules="rules"
           label-width="80px"
           label-position="top"
           ref="form">
    <el-form-item :label="$t('custom.reports.name')"
                  prop="name">
      <el-input :placeholder="$t('custom.mapping.enter')"
                v-model.trim="form.name">
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary"
                 class="el-button--full el-button--mt"
                 size="small"
                 :loading="loading"
                 @click="handleSubmit">
        {{ $t('custom.workSchedule.template.addBtn') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import ValidateMixin from '../mixins/validate.mixin'
import { get } from 'lodash'
export default {
  name: 'AccountNodeFormAdd',
  mixins: [ValidateMixin],
  props: {
    account: {
      type: Object,
      default: () => ({})
    },
    template: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      form: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: this.limitLargeNameLength, trigger: 'blur' }
        ]
      },
      loading: false
    }
  },

  methods: {
    async handleSubmit () {
      try {
        this.loading = true
        const value = await this.$refs.form.validate()
        if (value) {
          const { addAccount } = this.$interface.mapping
          const { name } = this.form
          const params = {
            accountId: get(this.template, 'id', ''),
            label: name,
            pid: get(this.account, 'id', '')
          }
          const { data: response } = await addAccount(params)
          if (response.code !== 0) {
            throw get(response, 'msg', '')
          }

          this.$emit('success')
          this.$message.success(this.$t('success'))
        }
      } catch (error) {
        error && this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    resetFields () {
      this.$refs.form.resetFields()
      this.form = {
        name: ''
      }
    }
  }
}
</script>
